import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';

// 模拟 API 请求
const apiCall = (param: number) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(`API 请求参数 ${param} 完成`);
        }, 2000);
    });
};

const Print = () => {
    const [isVideoLooping, setIsVideoLooping] = useState(true);
    const videoRef = useRef<HTMLVideoElement>(null);
    const navigate = useNavigate();

    const [completedCount, setCompletedCount] = useState(0);
    const params = Array.from({ length: 10 }, (_, i) => i + 1);

    const callAPIsSequentially = async () => {
        let count = 0;
        for (let i = 0; i < params.length; i++) {
            await apiCall(params[i]);
            count++;
            setCompletedCount(count);
        }
    };

    useEffect(() => {
        // start play video and call apis sequentially
        handleVideoPlay();
        callAPIsSequentially();
    }, []);

    // Event for video playing.
    const handleVideoPlay = () => {
        const video = videoRef.current;
        if (video) {
            video.play().catch((error) => {
                console.error("Error when playing video", error);
            });
        }
    };

    // detect all apis are called.
    useEffect(() => {
        if (completedCount === params.length) {
            setIsVideoLooping(false);
        }
    }, [completedCount]);


    const handleVideoEnd = () => {
        navigate("/about");
    };

    /**
     * 为视频元素添加了一个 ended 事件监听器,
     * 当视频播放结束时,
     * 就会触发 handleVideoEnd 函数
     */
    useEffect(() => {
        const video = videoRef.current;
        if (video) {
            video.addEventListener("ended", handleVideoEnd);
            return () => {
                video.removeEventListener("ended", handleVideoEnd);
            };
        }
    }, [handleVideoEnd]);

    return (
        <>
            <div>
                <p>{completedCount} / {params.length}</p>
            </div>

            <div>
                <p>{`Printing ${completedCount} of ${params.length} bag tag(s).`}</p>
                <video
                    ref={videoRef}
                    controls
                    autoPlay
                    muted
                    loop={isVideoLooping}
                    width={860}
                    height={260}
                >
                    <source src="/ice-sea.mp4" type="video/mp4" />
                </video>
            </div>
        </>
    );
};

export default Print;
